# This file is executed on every boot (including wake-boot from deepsleep)
import esp
esp.osdebug(None)
import webrepl
webrepl.start()


import urequests
import network
import ujson
import utime
import logging
import json

SYS_ENV_VALUES ={}
logging.basicConfig(logging.DEBUG)
log = logging.getLogger("main")

def load_config(file = "cfg.json"):
    with open( file,'r') as f:
        config_s = f.read()
        SYS_ENV_VALUES.update(ujson.loads(config_s))
        log.info(SYS_ENV_VALUES)

class Update:
    def __init__(self):
        pass
    def download_file(self,uri):
        r = urequests.get(uri)
        with open("a.py", 'wb') as f:
            f.write(r.content)

    def start(self ):
        d = {"mv": "my version",
             "rv": "request version"}
        r= urequests.post('http://localhost:9001/update', d)
        r = r.json()
        if not r['rtn']=='':
            return 0
        self.download_file(r['uri'])

class TimeCounter():
    cnt1 =0
    @staticmethod
    def timeout( val=10):
        utime.sleep(1)
        TimeCounter.cnt1 += 1
        if TimeCounter.cnt1>val:
            TimeCounter.cnt1 =0
            #log.error("timeout")
            return  True

def do_connect():

    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect('SN2', 'aaaa1111')
        while not sta_if.isconnected() and not TimeCounter.timeout():
            pass
        else:
            log.error("timeout")
            print("time222222222")
            return 1
    print('network config:', sta_if.ifconfig())
    return 0

def do_access_point():
    ap_if = network.WLAN(network.AP_IF)
    ap_if.active(True)
    ap_if.ifconfig()
if __name__ == '__main__':

    import httpserver

    load_config()

    if do_connect() == 0:
        pass
    else:
        do_access_point()
    httpserver.web_ui()
    #Update().start()



